<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script>
        // 保存定时器状态的全局变量
        var timeout;

        function requestTask() {
            if (!timeout) {
                $.ajax({
                    url: '/dev/task',
                    type: 'GET',
                    dataType: 'text',
                    success: function (res) {
                        console.log(res)
                        var result = JSON.parse(res);
                        ajax(result.taskId)
                    },
                    error: function (e) {
                        alert("error")
                    }
                });
            } else {
                alert("请先等待其他任务完成！");
            }
        }

        /**
         * ajax模拟心跳检测，询问当前任务执行状态
         * @param taskId
         */
        function ajaxPolling(taskId) {
            timeout = setInterval(function () {
                $.ajax({
                    url: '/dev/check-task',
                    data: {'taskId': taskId},
                    type: 'GET',
                    dataType: 'text',
                    success: function (res) {
                        var $heartResult = $("#heart-result");
                        $heartResult.val($heartResult.val() + " \n " + res);

                        var result = JSON.parse(res);
                        console.log(result)
                        if (!result.flag) {
                            // 关闭定时器，并将timeout设置为null
                            clearInterval(timeout)
                            timeout = null
                        }
                    },
                    error: function (e) {
                        alert("error")
                    }
                });
            }, 2000);// 定时，每两秒请求一次
        }
    </script>
    <title>ajax-heart-check</title>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body style="margin: 20px auto">
    <sapn>请求 <b>/task</b> 接口：</sapn><input type="button" onclick="requestTask()" value="请求task">
    <fieldset>
        <legend>心跳状态</legend>
        <textarea id="heart-result" style="border:2px solid red;height: 300px;width: 50%"></textarea>
    </fieldset>
</body>
</html>